//
//  Locatianmanager.m
//  work
//
//  Created by 方伟 on 16/6/15.
//  Copyright © 2016年 方伟. All rights reserved.
//
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "Locatianmanager.h"
static Locatianmanager *instance = nil;

@implementation Locatianmanager

+(instancetype)shareManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:nil] init];
        
    });
    
    [instance initialize];
    return instance;
}

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    return [self shareManager];
}

-(id)copy
{
    return self;
}



-(void) initialize{
    
    //创建CLLocationManager对象
    self.locationManager = [[CLLocationManager alloc] init];
    //设置代理为自己
    self.locationManager.delegate = self;
    
    
    
    if ([CLLocationManager locationServicesEnabled] == NO) {
        
        NSLog(@"没有GPS服务");
        
        
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"警告" message:@"没有开启定位服务" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        
        [alertView show];
        
        
        
        return;
        
    }

    //设置精度
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    //如果iOS8以后需要授权
    if ([[UIDevice currentDevice].systemVersion floatValue] > 8.0) {
        [_locationManager requestWhenInUseAuthorization];
    }
    
  
    
}
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"--------%f", newLocation.coordinate.latitude);
    NSLog(@"--------%f", newLocation.coordinate.longitude);
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
    
    
    NSString*longitude =[NSString stringWithFormat:@"%f", newLocation.coordinate.longitude];
    NSString*latitude =[NSString stringWithFormat:@"%f", newLocation.coordinate.latitude];

    if ([self.delegate respondsToSelector:@selector(returnlongitude:withlatitude:)]) {
       
        [self.delegate returnlongitude:longitude withlatitude:latitude];
    }
    

    
}

//- (void)locationManager:(CLLocationManager *)manager
//     didUpdateLocations:(NSArray *)locations
//{
//    NSLog(@"longitude = %f", ((CLLocation *)[locations
//                                             lastObject]).coordinate.longitude);
//    NSLog(@"latitude = %f", ((CLLocation *)[locations lastObject]).coordinate.latitude);
//    
//    [manager stopUpdatingLocation];
//}

-(void)startLocation{

    //开始定位
    [_locationManager startUpdatingLocation];
}
@end
